import { ForbiddenException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as argon2 from 'argon2';
import { UserService } from './../user/user.service';
import { SignupUserDto } from './dto/signup-user.dto';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  /**
   * 用户登录
   * 密码加密
   * 添加 token
   * @param username 用户名
   * @param password 密码
   */
  async signin(username: string, password: string) {
    if (!username || !password) {
      throw new ForbiddenException('用户名或密码不能为空');
    }

    const user = await this.userService.find(username);

    if (!user) {
      throw new ForbiddenException('用户不存在');
    }

    const isPasswordCorrect = await argon2.verify(user.password, password);

    if (!isPasswordCorrect) {
      throw new ForbiddenException('用户名或密码错误');
    }

    return await this.jwtService.signAsync({
      username: user.username,
      sub: user.id,
    });
  }

  /**
   * 注册用户
   * @param username 用户名
   * @param password 密码
   */
  async signup(userDto: SignupUserDto) {
    if (!userDto.username || !userDto.password) {
      throw new ForbiddenException('用户名或密码不能为空');
    }

    const user = await this.userService.find(userDto.username);

    if (user) {
      throw new ForbiddenException('用户名重复');
    }

    userDto.password = await argon2.hash(userDto.password);
    const res = await this.userService.create(userDto);

    return res;
  }
}
